<template>
  <view class="image-card" @click="handleClick">
    <view class="image-wrapper">
      <image
        :src="image.thumbnail || image.image"
        mode="aspectFill"
        class="card-image"
        :lazy-load="lazyLoad"
        @load="onImageLoad"
        @error="onImageError"
      />
      <view class="image-overlay">
        <view class="image-info">
          <text class="image-title">{{ image.title || "图片" }}</text>
        </view>
      </view>
    </view>
    <view class="card-footer">
      <view class="action-btn" @click.stop="toggleFavorite">
        <text class="icon" :class="{ active: isFav }">{{
          isFav ? "❤️" : "🤍"
        }}</text>
      </view>
      <view class="action-btn" @click.stop="downloadImage">
        <text class="icon">⬇️</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed } from "vue";
import { useImageStore } from "@/stores/image";
import { useUserStore } from "@/stores/user";
import { addFavorite as addFavoriteApi, removeFavorite as removeFavoriteApi } from "@/api/favorite";
import { showRewardVideoAd } from "@/utils/ad-manager";

const props = defineProps({
  image: {
    type: Object,
    required: true,
  },
  lazyLoad: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(["click"]);

const imageStore = useImageStore();
const userStore = useUserStore();

const isFav = computed(() => {
  return imageStore.isFavorite(props.image.id);
});

function handleClick() {
  emit("click", props.image);
  // 增加浏览计数
  imageStore.incrementBrowseCount();
}

async function toggleFavorite() {
  // 确保已登录
  if (!userStore.isLoggedIn) {
    try {
      // #ifdef H5
      await userStore.loginAsGuest();
      // #endif
      // #ifdef MP-WEIXIN
      await userStore.loginWithWeixin();
      // #endif
    } catch (err) {
      console.error('登录失败:', err);
      uni.showToast({
        title: '登录失败，请稍后重试',
        icon: 'none'
      });
      return;
    }
  }

  if (isFav.value) {
    // 取消收藏
    removeFavoriteApi(props.image.id).then(() => {
      imageStore.removeFavorite(props.image.id);
      uni.showToast({
        title: "已取消收藏",
        icon: "success",
      });
    }).catch(err => {
      console.error('取消收藏失败:', err);
      uni.showToast({
        title: err.message || "操作失败",
        icon: "none",
      });
    });
  } else {
    // 添加收藏
    addFavoriteApi(props.image.id).then(() => {
      imageStore.addFavorite(props.image);
      uni.showToast({
        title: "收藏成功",
        icon: "success",
      });
    }).catch(err => {
      console.error('添加收藏失败:', err);
      uni.showToast({
        title: err.message || "操作失败",
        icon: "none",
      });
    });
  }
}

function downloadImage() {
  // 下载需要看激励视频广告
  showRewardVideoAd(() => {
    // 下载图片
    uni.downloadFile({
      url: props.image.image,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              uni.showToast({
                title: "保存成功",
                icon: "success",
              });
            },
            fail: () => {
              uni.showToast({
                title: "保存失败",
                icon: "none",
              });
            },
          });
        }
      },
      fail: () => {
        uni.showToast({
          title: "下载失败",
          icon: "none",
        });
      },
    });
  });
}

function onImageLoad() {
  // 图片加载成功
}

function onImageError() {
  // 图片加载失败，可以显示占位图
  console.error("图片加载失败:", props.image.image);
}
</script>

<style scoped>
.image-card {
  background-color: #fff;
  border-radius: 10rpx;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.image-wrapper {
  position: relative;
  width: 100%;
  padding-top: 133.33%; /* 3:4 比例 */
  overflow: hidden;
}

.card-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.image-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.6), transparent);
  padding: 20rpx;
}

.image-info {
  display: flex;
  align-items: center;
}

.image-title {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}

.card-footer {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
}

.icon {
  font-size: 40rpx;
}

.icon.active {
  color: #ff4757;
}
</style>
